<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, shallowRef, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { ArrowLeft, Edit, Delete, Share, Download, View, More, FullScreen, Search } from '@element-plus/icons-vue'
// 导入wangeditor依赖
import '@wangeditor/editor/dist/css/style.css'
import { IDomEditor, Boot } from '@wangeditor/editor'
import { Editor } from '@wangeditor/editor-for-vue'
// 导入markdown插件
import markdownModule from '@wangeditor/plugin-md'
// Import card service functions with renamed aliases
import { getCard as getCardFromStorage, saveCard as saveCardToStorage, deleteCard as deleteCardFromStorage } from '../services/cardService'
import type { CardItem } from '../types/cardData'
// 导入导航历史工具
import { getBackRouteName } from '../utils/navigation'
// 导入编辑器配置
import { getWangEditorConfig } from '../utils/editorConfig'
import { formatDateTimeSync } from '../utils/dateFormatter'
// 导入外部链接处理工具
import { openExternalUrl } from '../utils/urlHandler'

// 注册markdown插件
Boot.registerModule(markdownModule)

// 路由
const router = useRouter()
const route = useRoute()

const { t } = useI18n()

// 卡片信息
const card = ref<CardItem>({
  id: '',  // Changed from number to string
  title: '',
  content: '',
  markdown: '',
  tags: [],
  created: '',
  updated: '',
  startTime: '',
  isStarred: false
})

// 页面状态
const loading = ref(true)
// 使用计算属性来确保总是从card上获取当前的isStarred值
const isStarred = computed(() => card.value.isStarred)
const showDropdown = ref(false)
const isFullScreen = ref(false)
const showMarkdown = ref(false) // 是否展示markdown源码
const wordCount = ref(0) // 添加字数统计
const showDownloadOptions = ref(false) // 添加下载选项显示状态

// wangeditor编辑器实例
const editorRef = shallowRef<IDomEditor | null>(null)
// HTML内容
const html = ref(`<p>${t('common.loading')}</p>`)

// 获取基础编辑器配置
const baseEditorConfig = getWangEditorConfig()

// 编辑器配置
const editorConfig = {
  readOnly: true,
  autoFocus: false,
  scroll: true,
  placeholder: '',
  MENU_CONF: baseEditorConfig.MENU_CONF,
  // 添加链接点击事件处理器
  EXTEND_CONF: {
    linkClickBehavior: (href: string) => {
      // 如果是http或https开头的链接，则使用外部浏览器打开
      if (href.startsWith('http://') || href.startsWith('https://')) {
        try {
          // 阻止默认行为
          event?.preventDefault();
          // 使用我们的工具函数打开外部链接
          openExternalUrl(href).catch(error => {
            console.error('打开外部链接失败:', error);
            ElMessage.error(t('viewCard.openUrlFailed'));
          });
          return false; // 阻止编辑器默认行为
        } catch (error) {
          console.error('处理链接点击失败:', error);
        }
      }
      return true; // 对于其他链接使用默认行为
    }
  }
}
// 编辑器模式
const mode = 'default'

// 自定义CSS样式
const customStyle = {
  textAlign: 'left'
}

// 修改获取卡片详情的方法
const fetchCardDetail = async () => {
  loading.value = true

  try {
    const cardId = route.params.id as string
    const data = await getCardFromStorage(cardId)

    if (data) {
      card.value = {
        ...data,
        isStarred: data.isStarred || false
      }
      html.value = data.content

      // 计算字数
      calculateWordCount(data.markdown || '')

      // 确保编辑器加载后内容是左对齐的
      setTimeout(() => {
        const editorDOM = document.querySelector('.w-e-text-container [data-slate-editor]')
        const textElements = document.querySelectorAll('.w-e-text p, .w-e-text h1, .w-e-text h2, .w-e-text h3')

        if (editorDOM) {
          ; (editorDOM as HTMLElement).style.textAlign = 'left'
        }

        if (textElements && textElements.length > 0) {
          textElements.forEach(el => {
            (el as HTMLElement).style.textAlign = 'left'
          })
        }
      }, 300)
    } else {
      ElMessage.error(t('viewCard.cardNotFound'))
      router.push('/')
    }
  } catch (error) {
    console.error('获取卡片详情失败:', error)
    ElMessage.error(t('viewCard.fetchFailed'))
  } finally {
    loading.value = false
  }
}

// 计算字数统计
const calculateWordCount = (text: string) => {
  if (!text) {
    wordCount.value = 0
    return
  }
  
  // 移除Markdown语法标记和HTML标签
  const cleanText = text
    .replace(/```[\s\S]*?```/g, '') // 移除代码块
    .replace(/`[^`]*`/g, '') // 移除行内代码
    .replace(/!\[.*?\]\(.*?\)/g, '') // 移除图片
    .replace(/\[.*?\]\(.*?\)/g, '') // 移除链接
    .replace(/<\/?[^>]+(>|$)/g, '') // 移除HTML标签
    .replace(/[#*_~`>]/g, '') // 移除Markdown标记符号
    .replace(/\s+/g, ' ') // 将多个空白字符替换为单个空格
    .trim()
  
  // 中文字符计数 + 英文单词计数
  const chineseCount = (cleanText.match(/[\u4e00-\u9fa5]/g) || []).length
  const englishWords = cleanText.replace(/[\u4e00-\u9fa5]/g, '').trim().split(/\s+/).filter(Boolean).length
  
  wordCount.value = chineseCount + englishWords
}

// 切换显示模式（HTML/Markdown）
const toggleViewMode = () => {
  showMarkdown.value = !showMarkdown.value
  ElMessage.success(showMarkdown.value ? t('viewCard.markdownView') : t('viewCard.textView'))
}

// 返回上一页
const goBack = () => {
  // 使用导航历史返回到相应的来源页面
  const backRouteName = getBackRouteName();
  router.push({ name: backRouteName });
}

// 编辑卡片
const editCard = () => {
  router.push(`/editor/${card.value.id}`)
}

// 修改删除卡片的方法
const handleDelete = () => {
  ElMessageBox.confirm(
    t('viewCard.deleteConfirm'),
    t('common.delete'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteCardFromStorage(card.value.id)
      ElMessage.success(t('viewCard.deleteSuccess'))
      router.push('/')
    } catch (error) {
      console.error('删除卡片失败:', error)
      ElMessage.error(t('viewCard.deleteFailed'))
    }
  }).catch(() => {
    // 用户取消删除操作
  })
}

// 分享卡片
const shareCard = () => {
  // 实际开发中应实现分享功能
  ElMessage.info(t('viewCard.shareDeveloping'))
}

// 修改收藏/取消收藏卡片的方法
const toggleStar = async () => {
  try {
    const updatedCard = await saveCardToStorage({
      ...card.value,
      isStarred: !card.value.isStarred
    })
    card.value = updatedCard
    ElMessage.success(isStarred.value ? t('common.saved') : t('common.unsaved'))
  } catch (error) {
    console.error('更新收藏状态失败:', error)
    ElMessage.error(t('common.updateFailed'))
  }
}

// 下载HTML文件
const downloadHtml = () => {
  try {
    const htmlContent = card.value.content || '';
    if (!htmlContent) {
      ElMessage.warning(t('viewCard.noContentToDownload'));
      return;
    }
    
    // 创建Blob对象
    const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 设置文件名为卡片标题(如果没有标题则使用默认名称)
    const filename = `${card.value.title || 'untitled'}.html`;
    link.download = filename;
    
    // 添加下载完成监听器
    let downloadingMessage: any = null;
    link.addEventListener('click', () => {
      // 显示下载中提示
      downloadingMessage = ElMessage({
        message: t('viewCard.downloading'),
        type: 'info',
        duration: 0
      });
    });
    
    // 模拟点击下载
    document.body.appendChild(link);
    
    // 使用后台线程模拟下载完成事件
    setTimeout(() => {
      // 关闭下载中提示
      if (downloadingMessage) {
        downloadingMessage.close();
      }
      // 显示下载成功提示
      ElMessage.success(t('viewCard.downloadSuccess'));
      
      // 清理
      URL.revokeObjectURL(url);
      document.body.removeChild(link);
    }, 1500); // 给予足够的时间来模拟下载过程
    
    link.click();
  } catch (error) {
    console.error('下载HTML失败:', error);
    ElMessage.error(t('viewCard.downloadFailed'));
  }
}

// 下载Markdown文件
const downloadMarkdown = () => {
  try {
    const markdownContent = card.value.markdown || '';
    if (!markdownContent) {
      ElMessage.warning(t('viewCard.noMarkdownContent'));
      return;
    }
    
    // 创建Blob对象
    const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    const filename = `${card.value.title || 'untitled'}.md`;
    link.download = filename;
    
    // 添加下载完成监听器
    let downloadingMessage: any = null;
    link.addEventListener('click', () => {
      // 显示下载中提示
      downloadingMessage = ElMessage({
        message: t('viewCard.downloading'),
        type: 'info',
        duration: 0
      });
    });
    
    document.body.appendChild(link);
    
    // 使用后台线程模拟下载完成事件
    setTimeout(() => {
      // 关闭下载中提示
      if (downloadingMessage) {
        downloadingMessage.close();
      }
      // 显示下载成功提示
      ElMessage.success(t('viewCard.downloadSuccess'));
      
      // 清理
      URL.revokeObjectURL(url);
      document.body.removeChild(link);
    }, 1500); // 给予足够的时间来模拟下载过程
    
    link.click();
  } catch (error) {
    console.error('下载Markdown失败:', error);
    ElMessage.error(t('viewCard.downloadFailed'));
  }
}

// 切换显示下载选项
const toggleDownloadOptions = (e: Event) => {
  e.stopPropagation(); // 阻止事件冒泡
  showDownloadOptions.value = !showDownloadOptions.value;
}

// 关闭下载选项
const closeDownloadOptions = () => {
  showDownloadOptions.value = false;
}

// 切换全屏
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value

  if (isFullScreen.value) {
    document.documentElement.requestFullscreen().catch(err => {
      console.error(`${t('viewCard.fullscreenFailed')}: ${err.message}`)
    })
  } else if (document.fullscreenElement) {
    document.exitFullscreen().catch(err => {
      console.error(`${t('viewCard.exitFullscreenFailed')}: ${err.message}`)
    })
  }
}

// 切换下拉菜单
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

// 关闭下拉菜单
const closeDropdown = () => {
  showDropdown.value = false
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  return formatDateTimeSync(dateString);
}

// 销毁wangeditor实例
const handleDestroy = () => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
}

// 添加窗口大小调整监听
const handleResize = () => {
  // 动态调整内容区域高度
  if (document.querySelector('.doc-content')) {
    const header = document.querySelector('.doc-header')
    const footer = document.querySelector('.doc-footer')
    const headerHeight = header ? header.clientHeight : 50
    const footerHeight = footer ? footer.clientHeight : 36
    const windowHeight = window.innerHeight
    
    // 设置内容区域的高度
    const contentWrapper = document.querySelector('.doc-content-wrapper')
    if (contentWrapper) {
      const contentHeight = windowHeight - headerHeight - footerHeight
      contentWrapper.setAttribute('style', `height: ${contentHeight}px`)
    }
  }
}

onMounted(() => {
  fetchCardDetail()

  // Add click outside event listeners to close dropdowns
  document.addEventListener('click', closeDropdown)
  document.addEventListener('click', closeDownloadOptions)

  // Listen for fullscreen changes
  document.addEventListener('fullscreenchange', () => {
    isFullScreen.value = !!document.fullscreenElement
  })
  
  // Add window resize listener
  window.addEventListener('resize', handleResize)
  
  // Run handleResize immediately instead of with delay
  handleResize()
})

// 组件销毁时清理事件监听和编辑器实例
onBeforeUnmount(() => {
  document.removeEventListener('click', closeDropdown)
  document.removeEventListener('click', closeDownloadOptions)
  document.removeEventListener('fullscreenchange', () => { })
  // 移除窗口大小调整监听
  window.removeEventListener('resize', handleResize)
  handleDestroy()
})
</script>

<template>
  <div class="view-card-container" :class="{ 'is-fullscreen': isFullScreen }">
    <!-- 顶部导航栏 -->
    <div class="doc-header">
      <div class="header-left">
        <div class="back-button" @click="goBack">
          <el-icon>
            <ArrowLeft />
          </el-icon>
        </div>
        <div class="doc-info">
          <h1 class="doc-title">{{ card.title }}</h1>
        </div>
      </div>

      <div class="header-center">
        <span class="doc-time">{{ formatDate(card.updated).split(' ')[0] }} {{ formatDate(card.updated).split(' ')[1] }}
          {{ t('viewCard.lastUpdated') }}</span>
      </div>

      <div class="header-right">
        <div class="action-group">
          <el-button 
            v-for="tag in card.tags" 
            :key="tag" 
            size="small" 
            class="action-tag"
            :style="card.tagColors && card.tagColors[tag] ? 
              {backgroundColor: card.tagColors[tag] + '33', borderColor: card.tagColors[tag], color: card.tagColors[tag]} : 
              {}"
          >
            {{ tag }}
          </el-button>
        </div>

        <div class="action-buttons">
          <div class="action-button" @click="toggleStar" :title="t('common.save')">
            <el-icon>
              <component :is="isStarred ? 'StarFilled' : 'Star'" />
            </el-icon>
          </div>
          <div class="action-button" @click="editCard" :title="t('viewCard.editDoc')">
            <el-icon>
              <Edit />
            </el-icon>
          </div>
          <!-- 下载按钮及下拉菜单 -->
          <div class="action-button download-trigger" @click.stop="toggleDownloadOptions" :title="t('viewCard.download')">
            <el-icon>
              <Download />
            </el-icon>
            
            <!-- 下载选项下拉菜单 -->
            <div v-if="showDownloadOptions" class="download-options-menu" @click.stop>
              <div class="download-option" @click="downloadHtml">
                {{ t('viewCard.downloadHtml') }}
              </div>
              <div class="download-option" @click="downloadMarkdown">
                {{ t('viewCard.downloadMarkdown') }}
              </div>
            </div>
          </div>
          <div class="action-button" @click="toggleFullScreen" :title="t('viewCard.fullscreen')">
            <el-icon>
              <FullScreen />
            </el-icon>
          </div>
          <div class="action-button dropdown-trigger" @click.stop="toggleDropdown" :title="t('common.more')">
            <el-icon>
              <More />
            </el-icon>

            <!-- 下拉菜单 -->
            <div v-if="showDropdown" class="dropdown-menu" @click.stop>
              <div class="dropdown-item" @click="editCard">
                <el-icon>
                  <Edit />
                </el-icon>{{ t('viewCard.editDoc') }}
              </div>
              <div class="dropdown-item" @click="shareCard">
                <el-icon>
                  <Share />
                </el-icon>{{ t('viewCard.share') }}
              </div>
              <div class="dropdown-item" @click="toggleFullScreen">
                <el-icon>
                  <FullScreen />
                </el-icon>{{ t('viewCard.fullscreen') }}
              </div>
              <div class="dropdown-item danger" @click="handleDelete">
                <el-icon>
                  <Delete />
                </el-icon>{{ t('common.delete') }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="doc-content-wrapper">
      <div class="doc-content" v-loading="loading">
        <div v-if="loading" class="loading-placeholder">{{ t('common.loading') }}</div>
        <template v-else>
          <!-- Markdown源码视图 -->
          <div v-if="showMarkdown" class="markdown-view">
            <pre><code>{{ card.markdown }}</code></pre>
          </div>
          <!-- WangEditor 内容展示区域 -->
          <div v-else class="editor-container">
            <Editor v-model="html" :defaultConfig="editorConfig" :mode="mode" style="height: 100%"
              :styleWithCss="customStyle" @onCreated="editorRef = $event" />
          </div>
        </template>
      </div>


    </div>

    <!-- 底部状态栏 -->
    <div class="doc-footer">
      <div class="footer-left">
        <span class="creation-info">{{ t('viewCard.startTime') }}: {{ formatDate(card.startTime) }} | {{
          t('viewCard.createdAt') }} {{ formatDate(card.created) }}</span>
      </div>
      <div class="footer-right">
        <span class="word-count-info">{{ wordCount }} {{ t('viewCard.wordCount') }}</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.view-card-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f9f9f9;
  color: #333;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  position: relative;
  overflow: hidden;
}

/* 顶部导航栏 */
.doc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  background-color: white;
  border-bottom: 1px solid #eaeaea;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 100;
  height: 50px;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 0 0 auto;
  min-width: 0;
  max-width: 30%;
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  flex-shrink: 0;
}

.back-button:hover {
  background-color: #f5f5f5;
}

.doc-info {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.doc-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
  line-height: 1.5;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-center {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.doc-time {
  white-space: nowrap;
  font-weight: 400;
  font-size: 12px;
  color: #86909c;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
  flex: 0 0 auto;
  min-width: 0;
  max-width: 40%;
}

.action-group {
  display: flex;
  gap: 8px;
}

.action-tag {
  margin: 0;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  color: #646a73;
  transition: all 0.2s;
}

.action-button:hover {
  background-color: #f5f5f5;
  color: #1e80ff;
}

/* 下拉菜单 */
.dropdown-trigger {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 36px;
  right: 0;
  width: 160px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  padding: 8px 0;
  z-index: 200;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f5f5f7;
}

.dropdown-item.danger {
  color: #f56c6c;
}

.dropdown-item.danger:hover {
  background-color: #fef0f0;
}

/* 主要内容区域 */
.doc-content-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  background-color: #f9f9f9;
  width: 100%;
  justify-content: center;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  overflow-y: auto;
}

.doc-content {
  flex: 1;
  background-color: white;
  padding: 40px 80px;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  max-width: 1400px;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #86909c;
  font-size: 16px;
}

/* WangEditor容器 */
.editor-container {
  height: 100%;
  min-height: 500px;
}

/* 右侧工具栏 */
.doc-toolbar {
  width: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  gap: 12px;
  position: fixed;
  right: 20px;
  top: 70px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  z-index: 90;
  max-height: calc(100vh - 140px);
  overflow-y: auto;
}



.content-body {
  line-height: 1.75;
  color: #1d2129;
  font-size: 16px;
}

/* 底部状态栏 */
.doc-footer {
  padding: 8px 16px;
  background-color: white;
  border-top: 1px solid #eaeaea;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #86909c;
  font-size: 12px;
  height: 36px;
  width: 100%;
  position: relative;
  z-index: 200;
  box-sizing: border-box;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.view-mode-label {
  font-size: 12px;
  color: #86909c;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

/* 编辑器相关样式 */
:deep(.w-e-text-container) {
  height: auto !important;
  min-height: 500px !important;
  background-color: white;
  text-align: left !important;
}

:deep(.w-e-text-placeholder) {
  color: #ccc;
}

:deep(.w-e-toolbar) {
  display: none !important;
}

:deep(.w-e-text-container [data-slate-editor]) {
  padding: 0 !important;
  overflow-y: hidden !important;
  text-align: left !important;
}

:deep(.w-e-text) {
  text-align: left !important;
}

:deep(.w-e-panel-content-color .w-e-panel-tab-content) {
  max-height: 350px !important;
}

/* 全屏模式 */
.is-fullscreen .doc-toolbar {
  top: 70px;
  right: 20px;
}

.is-fullscreen .doc-content {
  margin: 0 auto;
  max-width: 100% !important;
  width: 100% !important;
  border-radius: 0;
  box-shadow: none;
  padding: 40px;
  padding-bottom: 50px;
  /* 增加底部空间，避免遮挡 */
}

/* 富文本内容样式 */
.content-body :deep(h1),
:deep(.w-e-text-container) :deep(h1) {
  margin-top: 28px;
  margin-bottom: 16px;
  font-weight: 500;
  line-height: 1.4;
  color: #1d2129;
  font-size: 2em;
  margin-top: 0;

}

.content-body :deep(h2),
:deep(.w-e-text-container) :deep(h2) {
  font-size: 1.75em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
  margin-top: 28px;
  margin-bottom: 16px;
  font-weight: 500;
  line-height: 1.4;
  color: #1d2129;
}

.content-body :deep(h3),
:deep(.w-e-text-container) :deep(h3) {
  font-size: 1.5em;
  margin-top: 28px;
  margin-bottom: 16px;
  font-weight: 500;
  line-height: 1.4;
  color: #1d2129;
}

.content-body :deep(p),
:deep(.w-e-text-container) :deep(p) {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
}

.content-body :deep(ul),
.content-body :deep(ol),
:deep(.w-e-text-container) :deep(ul),
:deep(.w-e-text-container) :deep(ol) {
  margin-top: 0;
  margin-bottom: 16px;
  padding-left: 2em;
}

.content-body :deep(li),
:deep(.w-e-text-container) :deep(li) {
  margin-bottom: 8px;
  font-size: 16px;
}

.content-body :deep(blockquote),
:deep(.w-e-text-container) :deep(blockquote) {
  margin: 16px 0;
  padding: 12px 16px;
  color: #6a737d;
  border-left: 4px solid #dfe2e5;
  background-color: #f8f9fa;
  border-radius: 0 4px 4px 0;
  font-size: 16px;
}

.content-body :deep(pre),
:deep(.w-e-text-container) :deep(pre) {
  padding: 16px;
  overflow: auto;
  font-size: 14px;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 4px;
  margin: 16px 0;
}

.content-body :deep(code),
:deep(.w-e-text-container) :deep(code) {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 14px;
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 3px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

.content-body :deep(img),
:deep(.w-e-text-container) :deep(img) {
  max-width: 100%;
  box-sizing: content-box;
  background-color: #fff;
  border-radius: 4px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .view-card-container {
    background-color: #1a1a1a;
    color: #e0e0e0;
  }

  .doc-header,
  .doc-footer,
  .doc-sidebar,
  .doc-toolbar {
    background-color: #252525;
    border-color: #333;
  }

  .doc-title {
    color: #e0e0e0;
  }

  .doc-meta,
  .doc-footer {
    color: #a0a0a0;
  }

  .back-button:hover,
  .action-button:hover {
    background-color: #333;
  }

  .action-button {
    color: #a0a0a0;
  }

  .action-button:hover {
    color: #4e9eff;
  }

  .dropdown-menu {
    background-color: #252525;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  }

  .dropdown-item:hover {
    background-color: #333;
  }

  .dropdown-item.danger {
    color: #ff7875;
  }

  .dropdown-item.danger:hover {
    background-color: rgba(255, 77, 79, 0.15);
  }

  .doc-content-wrapper {
    background-color: #1a1a1a;
  }

  .doc-content {
    background-color: #252525;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }

  .content-body {
    color: #e0e0e0;
  }

  :deep(.w-e-text-container) {
    background-color: #252525 !important;
  }

  :deep(.w-e-text) {
    color: #e0e0e0 !important;
  }

  .content-body :deep(h1),
  .content-body :deep(h2),
  .content-body :deep(h3),
  :deep(.w-e-text-container) :deep(h1),
  :deep(.w-e-text-container) :deep(h2),
  :deep(.w-e-text-container) :deep(h3) {
    color: #e0e0e0;
  }

  .content-body :deep(h2),
  :deep(.w-e-text-container) :deep(h2) {
    border-color: #333;
  }

  .content-body :deep(blockquote),
  :deep(.w-e-text-container) :deep(blockquote) {
    color: #a0a0a0;
    border-left-color: #444;
    background-color: #2a2a2a;
  }

  .content-body :deep(pre),
  :deep(.w-e-text-container) :deep(pre) {
    background-color: #2a2a2a;
  }

  .content-body :deep(code),
  :deep(.w-e-text-container) :deep(code) {
    background-color: rgba(110, 118, 129, 0.3);
  }

  .content-body :deep(img),
  :deep(.w-e-text-container) :deep(img) {
    background-color: #333;
  }
}

/* 响应式设计 - 头部 */
@media (max-width: 768px) {
  .action-group {
    display: none;
  }

  .header-center {
    display: none;
  }

  .header-left {
    max-width: 50%;
  }

  .header-right {
    max-width: 50%;
  }

  .doc-footer {
    height: 44px;
    padding: 8px 12px;
  }

  .doc-content {
    padding: 20px;
    margin: 10px;
    width: calc(100% - 20px);
  }

  .doc-toolbar {
    display: none;
  }
}

/* Markdown视图样式 */
.markdown-view {
  padding: 0;
  overflow: auto;
  height: 100%;
}

.markdown-view pre {
  margin: 0;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.6;
  overflow: auto;
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 16px;
  white-space: pre-wrap;
  word-break: break-all;
  color: #333;
}

.markdown-view code {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

/* 暗色主题下的Markdown视图 */
@media (prefers-color-scheme: dark) {
  .view-mode-label,
  .word-count-info {
    background-color: #333;
    color: #a0a0a0;
  }

  .markdown-view pre {
    background-color: #2a2a2a;
    color: #e0e0e0;
  }
}

/* 添加字数统计样式 */
.word-count-info {
  font-size: 12px;
  color: #86909c;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

/* 下载选项菜单 */
.download-options-menu {
  position: absolute;
  top: 36px;
  right: 0;
  width: 160px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  padding: 8px 0;
  z-index: 201;
}

.download-option {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.download-option:hover {
  background-color: #f5f5f7;
}

/* 暗色主题下的下载选项 */
@media (prefers-color-scheme: dark) {
  .download-options-menu {
    background-color: #252525;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  }

  .download-option:hover {
    background-color: #333;
  }
}
</style>